import os

import GameState
import Interpreter
from Persistable import Persistable

pfile_dir = "%s/users/" % (os.getcwd())

def check_name(name):
    """Checks the pfile_dir for files with name"""
    return any(name.lower() in f.lower() for f in os.listdir(pfile_dir))

def get_pfile(username):
    return "%s%s.user" % (pfile_dir,username.lower())

class InvalidCredentials(Exception):
    """Exception for when username/password does not match"""


class DoesNotExist(Exception):
    """Exception for when a character does not exist"""


def load(username, password, new=False, skip_auth=False):
    """Factory method, loads a character from disk if not new, otherwise
       it will instantiate a new Character object"""
    return Character(username, password, new, skip_auth)


class Character(Persistable):

    def __init__(self, username, password, new=False, skip_auth=False, *args, **kwargs):
        super(Character, self).__init__( get_pfile(username), *args, **kwargs )
        # These are attributes that are persisted to disk
        # They become 'gettable' as if they were part of ch.__dict__
        # via overriding __getattr__ and __setattr__
        self.persistant = {
            "username": username,
            "password": password,
            "title": "the stupid newbie"
        }

        self.connection = None
        if not new:
            self.load(DoesNotExist)
            if not skip_auth and self.password != password:
                raise InvalidCredentials
        else:
            self.save()

    def to_self(self, message, *args, **kwargs):
        self.connection.to_self(message, *args, **kwargs)

    def interpret(self, args):
        """Send something to the interpreter as self"""
        Interpreter.interpret(self, args)


@Interpreter.command('who')
def who_command(ch, args):
    """
    Usage:
    who

    Displays a list of users currently connected.
    """
    buf = []
    buf.append( "${blue,bold}Who is connected to %s:${reset}" % "this simple game" )
    for player in GameState.get_playing():
        buf.append("%s, %s" % (player.username,player.title))
    ch.to_self("\n".join(buf))

@Interpreter.command('save')
def save(ch, args):
    """
    Usage:
    save

    Saves your character.
    """
    ch.save()
    ch.to_self("${yellow,bold}You have been saved. (praise the lord!)")

@Interpreter.command('title')
def title(ch, args):
    """
    Usage:
    title [new title]

    Displays your current title, or sets a new one.
    """
    if not len(args):
        ch.to_self("Your current title is: ${yellow,bold}%s" % ch.title)
    else:
        new_title = ' '.join(args).strip().replace("\t"," ")
        if len(new_title) < 40:
            ch.title = new_title
            ch.save()
            ch.to_self("Your title is now set to: ${yellow,bold}%s" % ch.title)
        else:
            ch.to_self("${yellow,bold}Titles must be fewer than 40 characters in length.")

